# TriggerSwitchD, executes commands to activate/deactive remote switches.
# (c) Copyright 2010 Pontus Strömdahl, AdhocSkill. 
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

module Tellstick
  #Proxy between usb dongle and driver
  class ProxyIO #:nodoc:all
    public
    def initialize(klass,*args)
      @init_args = args
      @class_to_proxy = klass
      @tio = nil
      open
    end
    
    def method_missing(method_id)
      @tio.send(method_id)
    end
    
    def open
      return unless @tio == nil
      create_io_instance
      attach_connected
      return if @tio.private_methods.include?("open")
      @tio.open
    end
    
    def close
      @tio.close unless @tio == nil
      @tio = nil
    end
    
    def puts(input)
      open
      @tio.puts(input)
      gets
    end
    
    def gets
      open
      @tio.gets
    end
    
    def to_s
      open
      @tio
    end
    private
    
    def create_io_instance
      if (@init_args.empty?)
        @tio = @class_to_proxy.new
      else
        @tio = @class_to_proxy.new(@init_args[0],@init_args[1])
        @init_args[2].call(@tio)
      end
    end
    
    def attach_connected
      if @tio.methods.include?("connected?")
        def self.connected?
          open
          @tio.connected?
        end
      end
    end
  end
end

